<template>
  <div class="dashboard-container">
    <!-- 顶部操作栏 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="24">
        <div class="dashboard-header">
          <h2>系统监控面板</h2>
          <div class="header-actions">
            <el-button type="primary" circle @click="refreshData">
              <el-icon><Refresh /></el-icon>
            </el-button>
            <el-button type="info" circle @click="settingsVisible = true">
              <el-icon><Setting /></el-icon>
            </el-button>
          </div>
        </div>
      </el-col>
    </el-row>
    
    <!-- 系统信息卡片 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="8">
        <el-card class="system-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>系统信息</span>
            </div>
          </template>
          <div class="info-list">
            <div class="info-item">
              <span class="label">操作系统：</span>
              <span class="value">{{ systemInfo?.platform }} {{ systemInfo?.arch }}</span>
            </div>
            <div class="info-item">
              <span class="label">主机名：</span>
              <span class="value">{{ systemInfo?.hostname }}</span>
            </div>
            <div class="info-item">
              <span class="label">系统版本：</span>
              <span class="value">{{ systemInfo?.release }}</span>
            </div>
            <div class="info-item">
              <span class="label">运行时间：</span>
              <span class="value">{{ systemInfo?.uptime }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="system-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>硬件信息</span>
            </div>
          </template>
          <div class="info-list">
            <div class="info-item">
              <span class="label">CPU型号：</span>
              <span class="value">{{ systemInfo?.cpus?.model }}</span>
            </div>
            <div class="info-item">
              <span class="label">CPU核心：</span>
              <span class="value">{{ systemInfo?.cpus?.cores }} 核</span>
            </div>
            <div class="info-item">
              <span class="label">内存总量：</span>
              <span class="value">{{ systemInfo?.memory?.total }}</span>
            </div>
            <div class="info-item">
              <span class="label">GPU：</span>
              <span class="value">{{ systemInfo?.gpu?.[0]?.name }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="system-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>网络信息</span>
            </div>
          </template>
          <div class="info-list">
            <div class="info-item">
              <span class="label">IP地址：</span>
              <span class="value">{{ systemInfo?.network?.address }}</span>
            </div>
            <div class="info-item">
              <span class="label">MAC地址：</span>
              <span class="value">{{ systemInfo?.network?.mac }}</span>
            </div>
            <div class="info-item">
              <span class="label">上传速度：</span>
              <span class="value">{{ systemLoad?.network?.txSpeed || '0 B/s' }}</span>
            </div>
            <div class="info-item">
              <span class="label">下载速度：</span>
              <span class="value">{{ systemLoad?.network?.rxSpeed || '0 B/s' }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 性能监控 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="12">
        <el-card class="system-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>CPU & 内存</span>
            </div>
          </template>
          <div class="info-list">
            <div class="info-item">
              <span class="label">CPU使用率：</span>
              <el-progress 
                :percentage="Number(systemLoad?.cpu?.average || 0)"
                :status="systemLoad?.cpu?.average > 80 ? 'exception' : 'normal'"
              />
            </div>
            <div class="info-item">
              <span class="label">内存使用率：</span>
              <el-progress 
                :percentage="Number(systemLoad?.memory?.usagePercent || 0)"
                :status="systemLoad?.memory?.usagePercent > 80 ? 'exception' : 'normal'"
              />
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="system-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>磁盘使用情况</span>
            </div>
          </template>
          <div class="info-list">
            <template v-if="systemInfo?.drives">
              <div v-for="drive in systemInfo.drives" :key="drive.name" class="info-item">
                <span class="label">{{ drive.name }}：</span>
                <el-progress 
                  :percentage="Number(drive.usagePercent)"
                  :status="drive.usagePercent > 90 ? 'exception' : drive.usagePercent > 70 ? 'warning' : 'normal'"
                  :format="() => `${drive.used} / ${drive.total}`"
                />
              </div>
            </template>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 进程列表 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="system-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>进程列表（Top 10）</span>
            </div>
          </template>
          <el-table :data="systemLoad?.processes || []" style="width: 100%" stripe>
            <el-table-column prop="name" label="进程名称" width="200" />
            <el-table-column prop="pid" label="进程ID" width="100" />
            <el-table-column prop="memoryUsage" label="内存占用" width="150" />
            <el-table-column label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getProcessStatus(row.memoryUsage)">
                  {{ getProcessStatusText(row.memoryUsage) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>

  <!-- 设置对话框 -->
  <el-dialog
    v-model="settingsVisible"
    title="系统设置"
    width="500px"
  >
    <el-form :model="settingsForm" label-width="120px">
      <el-form-item label="刷新间隔">
        <el-input-number
          v-model="settingsForm.refreshInterval"
          :min="1000"
          :max="10000"
          :step="1000"
          step-strictly
        >
          <template #suffix>ms</template>
        </el-input-number>
      </el-form-item>
      
      <el-form-item label="深色模式">
        <el-switch v-model="settingsForm.darkMode" />
      </el-form-item>
      
      <el-divider>告警阈值设置</el-divider>
      
      <el-form-item label="CPU告警阈值">
        <el-slider
          v-model="settingsForm.cpuThreshold"
          :min="50"
          :max="100"
          :marks="{
            50: '50%',
            70: '70%',
            90: '90%'
          }"
        />
      </el-form-item>
      
      <el-form-item label="内存告警阈值">
        <el-slider
          v-model="settingsForm.memoryThreshold"
          :min="50"
          :max="100"
          :marks="{
            50: '50%',
            70: '70%',
            90: '90%'
          }"
        />
      </el-form-item>
      
      <el-form-item label="磁盘告警阈值">
        <el-slider
          v-model="settingsForm.diskThreshold"
          :min="50"
          :max="100"
          :marks="{
            50: '50%',
            70: '70%',
            90: '90%'
          }"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancelSettings">取消</el-button>
        <el-button type="primary" @click="handleSaveSettings">
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.dashboard-container {
  padding: 20px;
  background-color: var(--el-bg-color);
  min-height: 100vh;
  transition: background-color 0.3s;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 0 10px;
}

.dashboard-header h2 {
  margin: 0;
  font-size: 28px;
  font-weight: 600;
  background: linear-gradient(45deg, var(--el-color-primary), var(--el-color-success));
  -webkit-background-clip: text;
  color: transparent;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
}

.header-actions {
  display: flex;
  gap: 12px;
}

.system-card {
  height: 100%;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border-radius: 12px !important;
  overflow: hidden;
}

.system-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1) !important;
}

.card-header {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  padding: 16px 20px !important;
  background: linear-gradient(to right, rgba(var(--el-color-primary-rgb), 0.1), transparent);
}

.info-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 8px;
  border-radius: 8px;
  transition: background-color 0.3s;
}

.info-item:hover {
  background-color: var(--el-fill-color-light);
}

.info-item .label {
  width: 120px;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  font-weight: 500;
}

.info-item .value {
  flex: 1;
  color: var(--el-text-color-primary);
  font-size: 14px;
  font-weight: 500;
}

.mb-4 {
  margin-bottom: 24px;
}

:deep(.el-progress) {
  flex: 1;
  margin-left: 12px;
}

:deep(.el-progress-bar__outer) {
  border-radius: 8px;
  background-color: var(--el-fill-color-light);
}

:deep(.el-progress-bar__inner) {
  border-radius: 8px;
  transition: all 0.3s ease-out;
}

:deep(.el-card) {
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05) !important;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: var(--el-bg-color-page);
  color: var(--el-text-color-primary);
  font-weight: 600;
  font-size: 14px;
}

:deep(.el-table td) {
  font-size: 14px;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: var(--el-fill-color-lighter);
}

:deep(.el-tag) {
  border-radius: 4px;
  padding: 4px 8px;
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 16px;
}

:deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  margin: 0;
  padding: 20px;
  background: linear-gradient(to right, var(--el-color-primary-light-7), var(--el-color-primary-light-9));
}

:deep(.el-dialog__title) {
  color: var(--el-color-primary);
  font-weight: 600;
  font-size: 20px;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-slider__runway) {
  margin: 16px 0;
}

:deep(.el-slider__bar) {
  transition: width 0.3s ease-out;
}

:deep(.el-slider__button) {
  transition: transform 0.3s ease-out;
}

:deep(.el-slider__button:hover) {
  transform: scale(1.2);
}

:deep(.el-divider__text) {
  font-weight: 500;
  color: var(--el-text-color-secondary);
}
</style>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useAppStore } from '@/stores/app'
import { ElMessage } from 'element-plus'

const store = useAppStore()

// 设置对话框
const settingsVisible = ref(false)
const settingsForm = ref({ ...store.settings })

// 系统信息和负载使用计算属性
const systemInfo = computed(() => store.systemInfo)
const systemLoad = computed(() => store.systemLoad)
const performanceHistory = computed(() => store.performanceHistory)

// 保存设置
async function handleSaveSettings() {
  if (await store.saveSettings(settingsForm.value)) {
    settingsVisible.value = false
    refreshData() // 使用新设置刷新数据
  }
}

// 取消设置
function handleCancelSettings() {
  settingsVisible.value = false
  settingsForm.value = { ...store.settings }
}

// 刷新数据
async function refreshData() {
  try {
    const info = await window.electron.getSystemInfo()
    const load = await window.electron.getSystemLoad()
    store.updateSystemInfo(info)
    store.updateSystemLoad(load)
    if (load && load.history) {
      store.updatePerformanceHistory(load.history)
    }
  } catch (error) {
    console.error('刷新数据失败:', error)
    ElMessage.error('刷新数据失败')
  }
}

// 组件挂载时
onMounted(async () => {
  // 加载设置
  await store.loadSettings()
  
  // 初始化数据
  await refreshData()
  
  // 监听性能更新
  if (window.electron) {
    window.electron.onPerformanceUpdate((data) => {
      store.updateSystemLoad(data)
      if (data.history) {
        store.updatePerformanceHistory(data.history)
      }
    })
  }
})

// 组件卸载时
onUnmounted(() => {
  if (window.electron) {
    window.electron.removePerformanceListener()
  }
})

// 获取进程状态
function getProcessStatus(memoryUsage) {
  const usage = parseInt(memoryUsage)
  if (usage > 500000) return 'danger'
  if (usage > 100000) return 'warning'
  return 'success'
}

// 获取进程状态文本
function getProcessStatusText(memoryUsage) {
  const usage = parseInt(memoryUsage)
  if (usage > 500000) return '高'
  if (usage > 100000) return '中'
  return '低'
}

// 导入图标
import { Setting, Refresh } from '@element-plus/icons-vue'
</script> 